<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义redux</title>
</head>
<body>
  <button onclick="dispatch({ type: 'reduce', payload: 15 })">-</button>
  <div id="count"></div>
  <button onclick="dispatch({ type: 'add', payload: 15 })">+</button>
</body>
<script>
  // 定义一个方法，用于集中管理state和dispatch
  const createStore = (state, changeState) => {
    // getState 获取状态
    const getState = () => {
      return state
    }

    // 定义一个监听器，用于管理一些方法
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
  
    // 定义一个dispatch方法，让每次有action传入的时候返回render执行之后的结果
    const dispatch = (action) => {
      // 调用changeState来处理数据
      changeState(state, action)
      // 让监听器里的所以方法运行
      listeners.forEach(listener => listener())
    }

    return {
      getState,
      dispatch,
      subscribe
    }
  }
  // 设置初始化状态
  const countState = {
    count: 10
  }
  // 定义一个方法用于渲染计数器的dom
  const renderCount = (state) => {
    const countDom = document.querySelector('#count')
    countDom.innerHTML = state.count
  }
  // 渲染默认数据
  renderCount(countState)

  // 分发
  function dispatch (action) {
    changeState(action) // 修改状态
    renderCount(countState) // 渲染数据
  }

  // 定义的纯函数，纯函数
  function changeState (action) {
    const { type, payload } = action
    switch (type) {
      case 'add': 
        countState.count += payload
        break
      case 'reduce':
        countState.count -= payload
        break
      default:
        countState
    }
  }

  // 创建状态管理
  const store = createStore(countState, changeState)
  // 订阅数据变化
  store.subscribe(renderCount)
  console.log(store.getState())
</script>
</html>